import { Box,AppBar, Toolbar, Typography, Alert } from "@mui/material";
import { useLoaderData, useParams } from "react-router-dom";
import FilesContainer from "../../components/FilesContainer/FilesContainer";
import ShareToolBar from "./ShareToolBar";
import { useEffect, useState } from "react";
import koalaLogo from '../../assets/imgs/koala_logo_100.png'

function SharePage() {
    const param = useParams();
    let {shared, sharedFiles} = useLoaderData();
    sharedFiles = sharedFiles.map(f => {let sele = f.selected === undefined ? false : f.selected; return {selected: false, ...f}})
    const [files, setFiles] = useState(sharedFiles);
    
    const [selectedFiles, setSelectedFiles] = useState([]);
    function changeParentId(item) {
        
    }
    function handleContextMenuOpen(e) {
        e.preventDefault()
        
    }
    function handleFileSelected(file, checked) {
        console.log(file, checked)
        let newFiles = []
        files.forEach((e)=> {
            if (e.id === file.id) {
                e.selected = checked;
            }
            newFiles.push(e)
        })
        setFiles(newFiles)
    }
    useEffect(()=> {
        let newSelectedFile = []
        files.forEach((e) => {
            if (e.selected) {
                newSelectedFile.push(e)
            }
        })
        setSelectedFiles(newSelectedFile)
    }, [files])

    return (
        <Box>
            <Box>
                <AppBar position="static">
                    <Toolbar>
                        <img alt='koala logo' src={koalaLogo} style={{height:'50px'}}/>
                        <Typography sx={{marginLeft:'8px', fontWeight:'800'}}>Koala Drive</Typography>
                    </Toolbar>
                </AppBar>
            </Box>
            
            <Box sx={{marginTop:'16px'}}>
                <ShareToolBar selectedFiles={selectedFiles} />
                {shared.msg ? 
                    <Box sx={{margin: '16px 32px', width:{md: '300px'}}}>
                        <Alert variant="filled" severity="info">
                            {shared.msg}
                        </Alert>
                    </Box> : 
                    <Box></Box>
                }
                <FilesContainer files={files} onClick={changeParentId} handleContextMenuOpen={handleContextMenuOpen} handleFileSelected={handleFileSelected} readOnly={true} />
            </Box>
            
        </Box>
    )
}

export default SharePage;